package com.test20_多线程应用;

/**
 * 电脑生产与消费
 * 面试题：设计一个生产电脑和搬运电脑类，要求生产出一台电脑就搬走一台电脑，并统计出生产的电脑数量
 */
public class YootkDemo_02 {

    public static void main(String[] args) {
        Resource2 resource = new Resource2();
        new Thread(() -> {
            for (int x = 0; x < 50; x++) {
                if (x % 2 == 0) {
                    resource.create("外星人 - " + x, 29999.0);
                } else {
                    resource.create("MacBook - " + x, 19999.0);
                }
            }
        }, "电脑生产者").start();
        new Thread(() -> {
            for (int x = 0; x < 50; x++) {
                resource.get();
            }
        }, "电脑搬运工").start();
    }
}

/** 公共的访问资源 */
class Resource2 {
    private int number = 0; // 统计电脑的数量
    private Computer computer;  // 描述生产或取走的电脑资源

    public Resource2() {
        Thread daemonThread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("【后台线程】当前生产的电脑数量为：" + this.number);
            }
        });
        daemonThread.setDaemon(true);   // 设置为后台线程
        daemonThread.start();
    }

    public synchronized void create(String brand, double price) {
        try {
            if (this.computer != null) {    // 已经创建完成，但是未取走
                super.wait();
            }
            this.computer = new Computer(brand, price);
            this.number++;
            Thread.sleep(100);
            System.out.println("【" + Thread.currentThread().getName() + "】电脑生产完成，" + this.computer);
            super.notify();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void get() {
        try {
            if (this.computer == null) {    // 等待生产
                super.wait();
            }
            Thread.sleep(100);
            System.out.println("【" + Thread.currentThread().getName() + "】搬运电脑，" + this.computer);
            this.computer = null;
            super.notify();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

/** 电脑实体类 */
class Computer {
    private String brand;   // 电脑品牌
    private double price;   // 电脑价格

    public Computer(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }

    @Override
    public String toString() {
        return "电脑品牌 = " + this.brand + "、电脑价格 = " + this.price;
    }
}
